package com.darksides.lenditweb.server;

import javax.xml.bind.JAXBElement;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

import com.darksides.lenditweb.client.bean.UserBean;
import com.darksides.lenditweb.client.service.UserService;
import com.darksides.lenditweb.server.model.User;
import com.darksides.lenditweb.shared.exceptions.user.EmailAlreadyUsedException;
import com.darksides.lenditweb.shared.exceptions.user.UserNotFoundException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;

/**
 * @author Benjamin Barbier
 *
 */
@SuppressWarnings( "serial" )
public class UserServiceImpl extends RemoteServiceServlet implements UserService {

	private final Mapper mapper = new DozerBeanMapper();
	private final String lendIdUserUrl = "http://lend-it.appspot.com/user/";
	private GenericType<JAXBElement<User>> userType = new GenericType<JAXBElement<User>>() {};
	private final Client restClient;
	
	public UserServiceImpl() {
		restClient = Client.create();
		restClient.setFollowRedirects(true);
	}
	
	public UserBean create( UserBean userBean ) throws EmailAlreadyUsedException {

		WebResource webResource = restClient.resource(lendIdUserUrl);
		User user = mapper.map(userBean, User.class);
		try {
			user = webResource.put(userType, user).getValue();
		} catch (UniformInterfaceException ue) {
			throw new EmailAlreadyUsedException();
		}
		UserBean result = mapper.map(user, UserBean.class);
		return result;
	}
	
	public UserBean get( String userId ) throws UserNotFoundException {
		
		WebResource webResource = restClient.resource(lendIdUserUrl + userId);
		User user = null;
		try {
			user = (User) webResource.get(userType).getValue();
		} catch (UniformInterfaceException ue) {
			throw new UserNotFoundException();
		}
		UserBean userBean = mapper.map(user, UserBean.class);
		return userBean;
	}
	
	public UserBean delete( String userId ) throws UserNotFoundException {
	
		WebResource webResource = restClient.resource(lendIdUserUrl + userId);
		User user = null;
		try {
			user = (User) webResource.delete(userType).getValue();
		} catch (Exception e) {
			throw new UserNotFoundException();
		}
		UserBean userBean = mapper.map(user, UserBean.class);
		return userBean;
	}
	
}
